import axios from "axios";
import { Toast } from "vant";
import store from "@/store";
import { getToken, removeToken, removeUserInfo } from "@/utils/auth";
import Router from "@/router/index";
import qs from "qs";
// create an axios instance 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 请求的基础路径（域名）在api的index.js中填写具体路径
  withCredentials: true, // 可解决跨域问题
  timeout: 5000, // 请求时长
});

// request interceptor 请求拦截器
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    const token = localStorage.getItem("token");
    //const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJwYXJlbnRUb2tlbjU0MzgzNTkiLCJpYXQiOjE2MDMxODk1NjcsImV4cCI6MTYwMzc5NDM2N30.sD4yLlu1ZWoM11ig1gPHGSrpInrJZaYXuplLU5e2H2l_DKZqf2uIT6JrBhGLXh4_nMsmwhnSmYj0b5UB3jvyVA'
    if (token) {
      config.headers["satoken"] = "Bearer " + token;
    }

    // // config.headers["Content-Type"] = "application/xml";
    store.commit("setLoading", true);
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error, "err"); // for debug
    store.commit("setLoading", false);
    return Promise.reject(error);
  }
);

// response interceptor 相应拦截器
service.interceptors.response.use(
  (res) => {
    store.commit("setLoading", false);
    if (res.data.code != 200) {
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.data.code == 4002) {
        removeToken();
        removeUserInfo();
        Router.push({
          path: "/login",
        });
        return Promise.reject("error");
      } else {
        Toast.fail({
          message: res.data.message,
          duration: 1.5 * 1000,
        });
        throw "error";
      }
    } else {
      return res.data;
    }
  },
  (error) => {
    store.commit("setLoading", false);
    console.log("err" + error); // for debug
    Toast.fail({
      message: error.message,
      duration: 1.5 * 1000,
    });
    return Promise.reject(error);
  }
);

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
service.paramsData = (
  data = {},
  openDefultdata = false,
  contentType = "json"
) => {
  var defaults = {
    t: new Date().getTime(),
  };
  data = openDefultdata ? merge(defaults, data) : data;
  return contentType === "json" ? JSON.stringify(data) : qs.stringify(data);
};

export default service;
